package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BdmBalanceChange;
import com.ruoyi.system.domain.BdmSignIn;
import com.ruoyi.system.domain.BdmUser;
import com.ruoyi.system.domain.vo.applet.AppletSignInVo;
import com.ruoyi.system.mapper.BdmSignInMapper;
import com.ruoyi.system.service.IBdmBalanceChangeService;
import com.ruoyi.system.service.IBdmSignInService;
import com.ruoyi.system.service.IBdmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 签到Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-13
 */
@Service
public class BdmSignInServiceImpl implements IBdmSignInService {
    @Autowired
    private BdmSignInMapper bdmSignInMapper;

    @Autowired
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private IBdmUserService bdmUserService;

    /**
     * 查询签到
     *
     * @param id 签到主键
     * @return 签到
     */
    @Override
    public BdmSignIn selectBdmSignInById(Long id) {
        return bdmSignInMapper.selectBdmSignInById(id);
    }

    /**
     * 查询签到列表
     *
     * @param bdmSignIn 签到
     * @return 签到
     */
    @Override
    public List<BdmSignIn> selectBdmSignInList(BdmSignIn bdmSignIn) {
        return bdmSignInMapper.selectBdmSignInList(bdmSignIn);
    }

    /**
     *
     */

    /**
     * 新增签到
     * 1. 查询是否有签到信息
     * 1.1 有判断是否连续签到 无进行首次签到
     * 2. 判断今天是否签到
     *
     * @return 结果
     */
    @Override
    @Transactional
    public AppletSignInVo insertBdmSignIn() {
        String score = "1";
        BdmSignIn signIn = new BdmSignIn();
        signIn.setSysUid(SecurityUtils.getUserId());
        List<BdmSignIn> signInList = bdmSignInMapper.selectBdmSignInList(signIn);

        Date signinTime = DateUtils.getNowDate();
        signIn.setSigninTime(DateUtils.getDate());
        signIn.setCreateTime(signinTime);
        if (StringUtils.isEmpty(signInList)) {
            // 首签
            signIn.setSigninType(0L);
            signIn.setDayNumber(1L);
            signIn.setScore(score);
            bdmSignInMapper.insertBdmSignIn(signIn);
        } else {
            String lastTime = signInList.get(0).getSigninTime();
            String nowTime = DateUtils.getDate();
            Date yesterday = DateUtils.addDays(new Date(), -1);
            String yesterdayTime = DateUtils.dateTime(yesterday);
            if (lastTime.equals(nowTime)) {
                // 已签到
                throw new GlobalException("今天已签到");
            } else if (lastTime.equals(yesterdayTime)) {
                // 连续签到
                signIn.setSigninType(1L);
                Long dayNumber = signInList.get(0).getDayNumber();
                signIn.setDayNumber(dayNumber + 1);
               // score = dayNumber + 1 >= 7 ? String.valueOf(Integer.parseInt(score) * 3) : score;
                signIn.setScore(score);
            } else {
                // 断签 重新签到
                signIn.setSigninType(0L);
                signIn.setDayNumber(1L);
                signIn.setScore(score);
            }
            bdmSignInMapper.insertBdmSignIn(signIn);
        }
        BdmBalanceChange bdmBalanceChange = bdmBalanceChangeService.lambdaQuery()
                .eq(BdmBalanceChange::getUserId, SecurityUtils.getUserId())
                .eq(BdmBalanceChange::getVariationType, 2L)
                .orderByDesc(BdmBalanceChange::getCreateTime)
                .last("limit 1")
                .one();
        boolean change = StringUtils.isNull(bdmBalanceChange);

        /*-------------------------签到记录积分明细----------------------------*/
        BdmBalanceChange balanceChange = BdmBalanceChange.builder()
                .userId(SecurityUtils.getUserId())
                .relevantDocumentId(signIn.getId().toString())
                .variation(signIn.getScore())
                .variationBefore(change ? "0" : bdmBalanceChange.getVariationAfter())
                .variationAfter(change ? signIn.getScore() : new BigDecimal(bdmBalanceChange.getVariationAfter()).add(new BigDecimal(signIn.getScore())).toString())
                .variationType(2L)
                .addOrSubtract(1L)
                .businessType("增加-签到积分获得")
                .createBy(SecurityUtils.getUserId().toString())
                .createTime(DateUtils.getNowDate())
                .updateBy(SecurityUtils.getUserId().toString())
                .updateTime(DateUtils.getNowDate())
                .build();
        bdmBalanceChangeService.insertBdmBalanceChange(balanceChange);

        /*-------------------------签到积分入住用户积分----------------------------*/
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, SecurityUtils.getUserId()).one();
        bdmUser.setCreditScore(new BigDecimal(StringUtils.isNotEmpty(bdmUser.getCreditScore()) ? bdmUser.getCreditScore() : "0" ).add(new BigDecimal(signIn.getScore())).toString());
        // 修改积分
        bdmUserService.lambdaUpdate().set(BdmUser::getCreditScore, bdmUser.getCreditScore()).eq(BdmUser::getId, bdmUser.getId()).update();
        return AppletSignInVo.builder()
                .totalScore(bdmUser.getCreditScore())
                .dayNumber(signIn.getDayNumber())
                .toDayStatus(false)
                .scoreNum(score)
                .build();
    }

    /**
     * 修改签到
     *
     * @param bdmSignIn 签到
     * @return 结果
     */
    @Override
    public int updateBdmSignIn(BdmSignIn bdmSignIn) {
        bdmSignIn.setUpdateTime(DateUtils.getNowDate());
        return bdmSignInMapper.updateBdmSignIn(bdmSignIn);
    }

    /**
     * 批量删除签到
     *
     * @param ids 需要删除的签到主键
     * @return 结果
     */
    @Override
    public int deleteBdmSignInByIds(Long[] ids) {
        return bdmSignInMapper.deleteBdmSignInByIds(ids);
    }

    /**
     * 删除签到信息
     *
     * @param id 签到主键
     * @return 结果
     */
    @Override
    public int deleteBdmSignInById(Long id) {
        return bdmSignInMapper.deleteBdmSignInById(id);
    }

    /**
     * 查询我的积分
     *
     * @return
     */
    @Override
    public AppletSignInVo selectMineScore() {
//        BdmBalanceChange bdmBalanceChange = bdmBalanceChangeService.lambdaQuery()
//                .eq(BdmBalanceChange::getUserId, SecurityUtils.getUserId())
//                .eq(BdmBalanceChange::getVariationType, 2L)
//                .orderByDesc(BdmBalanceChange::getCreateTime)
//                .last("limit 1")
//                .one();

        BdmSignIn signIn = new BdmSignIn();
        signIn.setSysUid(SecurityUtils.getUserId());
        List<BdmSignIn> signInList = bdmSignInMapper.selectBdmSignInList(signIn);
        Long dayNumber = 0L;
        boolean toDayStatus = true;
        if (StringUtils.isNotEmpty(signInList)) {
            BdmSignIn bdmSignIn = signInList.get(0);
            if (bdmSignIn.getSigninTime().equals(DateUtils.getDate())) {
                dayNumber = bdmSignIn.getDayNumber();
                toDayStatus = false;
            } else if (bdmSignIn.getSigninTime().equals(DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -1)))
                    && bdmSignIn.getSigninType() != 3) {
                dayNumber = bdmSignIn.getDayNumber();
            }
        }
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, SecurityUtils.getUserId()).one();
//      .totalScore(StringUtils.isNotNull(bdmBalanceChange) ? StringUtils.isNotEmpty(bdmBalanceChange.getVariationAfter()) ? bdmBalanceChange.getVariationAfter() : "0" : "0")
        return AppletSignInVo.builder()
                .totalScore(StringUtils.isNotEmpty(bdmUser.getCreditScore()) ? bdmUser.getCreditScore() : "0")
                .dayNumber(dayNumber)
                .toDayStatus(toDayStatus)
                .scoreNum(dayNumber >= 7 ? "30" : "10")
                .build();
    }
}
